#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
LastEditTime: 2024-10-29 17:53:49
Description: 程序运行计时工具
'''

__all__= []

import signal
class TimeoutException(Exception):
    def __str__(self) -> str:
        return "程序运行超时"
def timeout_handler(signum, frame):
    """
    超时后执行的方法
    :param signum:
    :param frame:
    :return:
    """
    raise TimeoutException
def set_timeout(func, timeout: int, *args, **kwargs):
    """
    给方法设置超时时间
    :param func:
    :param timeout:
    :return:
    """
    assert isinstance(timeout, int) and timeout > 0, "超时时间只能为非零正整数"
    signal.signal(signal.SIGALRM, timeout_handler)
    signal.alarm(timeout)
    try:
        res = func(*args, **kwargs)
    finally:
        signal.alarm(0)  # 清除超时设置，防止影响其他程序运行
    return res